package execution;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;

public class Tape implements Iterable<Byte>  {
	
	private TapeNode head, tail, current;
	private final PrintWriter os;
	private final InputStream is;
	
	@Override
	public Iterator<Byte> iterator() {
		return new TapeIterator(head);
	}
	
	public Tape() {
		head = new TapeNode();
		tail = head;
		current = head;
		os = new PrintWriter(System.out);
		is = System.in;
	}
	
	public Tape(OutputStream os, InputStream is) {
		head = new TapeNode();
		tail = head;
		current = head;
		this.os = new PrintWriter(os);
		this.is = is;
	}
	
	public void inc_ptr() {
		if (current.getRight() == null) {
			TapeNode newNode = new TapeNode();
			newNode.setLeft(current);
			current.setRight(newNode);
			tail = newNode;
		}
		current = current.getRight();
	}
	
	public void dec_ptr() {
		if (current.getLeft() == null) {
			TapeNode newNode = new TapeNode();
			newNode.setRight(current);
			current.setLeft(newNode);
			head = newNode;
		}
		current = current.getLeft();
	}
	
	public void inc() {
		current.inc();
	}
	
	public void dec() {
		current.dec();
	}
	
	public void out() {
		os.write((char) current.getDatum().byteValue());
	}
	
	public void in() throws IOException {
		current.setDatum((byte) is.read());
	}
	
	public Byte getDatum() {
		return current.getDatum();
	}

}
